﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class AddBook : System.Web.UI.Page
{
    private int Id = 0;
    private EbookDetail ebook;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Id"] != null)
        {
            Id = Convert.ToInt32(Request.QueryString["Id"]);
        }

        if (!IsPostBack)
        {
            ddlCategory.DataSource = Category.GetAllCategories();
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem("Select", "0"));

            ddlPublisher.DataSource = Publisher.GetAllPublishers();
            ddlPublisher.DataBind();
            ddlPublisher.Items.Insert(0, new ListItem("Select", "0"));

            if (Id > 0)
            {
                ebook = EbookDetail.GetEBooks(Id);
                txtTitle.Text = ebook.Title;
                txtSubTitle.Text = ebook.SubTitle;
                txtSummary.Text = ebook.Summary;
                txtEdition.Text = ebook.Edition;
                txtPublishedYear.Text = ebook.PublishedYear.ToString();

                ListItem iCat = ddlCategory.Items.FindByValue(ebook.CategoryId.ToString());
                ddlCategory.ClearSelection();
                iCat.Selected = true;

                ListItem iPub = ddlPublisher.Items.FindByValue(ebook.PublisherId.ToString());
                ddlPublisher.ClearSelection();
                iPub.Selected = true;

                txtAuthors.Text = ebook.Authors;
                txtLink.Text = ebook.Link;
            }
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (fuThumbnail.HasFile)
        {
            byte[] btImage = new byte[fuThumbnail.FileContent.Length];
            fuThumbnail.FileContent.Read(btImage, 0, btImage.Length);

            if (Id > 0)
            {
                ebook = EbookDetail.GetEBooks(Id);                
            }
            else
            {
                ebook = new EbookDetail();
                ebook.Id = 0;
            }

            ebook.Title = txtTitle.Text;
            ebook.SubTitle = txtSubTitle.Text;
            ebook.Summary = txtSummary.Text;
            ebook.Edition = txtEdition.Text;            
            ebook.Authors = txtAuthors.Text;
            ebook.PublisherId = Convert.ToInt32(ddlPublisher.SelectedValue);
            ebook.PublishedYear = Convert.ToInt32(txtPublishedYear.Text);
            ebook.CategoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            ebook.Link = txtLink.Text;

            ebook.SaveEbookDetail(btImage);
        }
    }
}